#coding:utf-8
from markdown import markdown
import flask,os,time
import shutil
app = flask.Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
MasterKey = "iambakabaka9qwq"
WebSiteTitle = "Is nothing for here"
WebSiteUrl="http://blog.9bie.org:8082"
def Data_compare(x, y):
    stat_x = os.stat( "Arichvers/"+x)
    stat_y = os.stat("Arichvers/"+y)
    if stat_x.st_ctime < stat_y.st_ctime:
        return -1
    elif stat_x.st_ctime > stat_y.st_ctime:
        return 1
    else:
        return 0
def parse(md_text):
    return markdown(md_text)
def CreadArichvers(Title,content):
    dirs = 'Arichvers/'+str(NewId(1))
    print NewId(1)
    error = os.mkdir(dirs)
    if error == -1:
        return -1
    try:
        title = open(dirs+"/title","w")
        title.write(Title.encode('utf-8'))
        title.close()
        data = open(dirs+"/data","w")
        data.write("emmmmmm")
        data.close()
        contents=open(dirs+"/content","w")
        contents.write(content.encode('utf-8'))
        contents.close()
    except:
        pass
def LoadArichversList():
    tempList = []
    files = os.listdir("Arichvers")
    files.sort(Data_compare)
    print files

    #print files
    for item in files:
        with open ("Arichvers/"+str(item)+"/title",'r') as titlefile:
            tempList.append({"href":"index/"+item,"title":titlefile.read().decode("utf-8"),"Data":ArichverData(str(item))[0]})

    return tempList
def NewId(i=1):
    '''files = os.listdir("Arichvers")
    if len(files) == 0:
        return 1
    else:
        return int(files[-1])+1'''
    #print os.path.isdir("Arichvers/"+str(i)),i
    if os.path.isdir("Arichvers/"+str(i)) == False:
        return i
    else:
        return NewId(i+1)
def ArichverData(id):
    f = "Arichvers/"+id+"/Data"
    mtime = time.ctime(os.path.getmtime(f))
    ctime = time.ctime(os.path.getctime(f))
    return [mtime,ctime]
@app.route('/')
@app.route('/<int:page>')
def index(page=1):
    #Arichvers_List = LoadArichversList()
    Arichvers_List = LoadArichversList()
    return flask.render_template("index.html",Arichvers_List=Arichvers_List,WebSiteTitle=WebSiteTitle,WebSiteUrl=WebSiteUrl)
@app.route('/index/<int:ArichversID>')
def ArichversPage(ArichversID):
    try:

        with open("Arichvers/"+str(ArichversID)+"/content") as Contents:
            Content = Contents.read()
            Content = Content.replace('\n',"<br>")
        with open("Arichvers/"+str(ArichversID)+"/title") as titles:
            title = titles.read()
    except:
        return "Error"
    else:
        return flask.render_template("page.html",WebSiteTitle=WebSiteTitle,WebSiteUrl=WebSiteUrl,Title=title.decode("utf-8"),Content=Content.decode("utf-8"))
@app.route('/login/<username>/<password>')#, methods=['GET', 'POST']
def login(password):
    '''if flask.request.method == 'POST':
        #session['username'] = request.form['username']
        if flask.request.form['password'] == MasterKey:
            flask.session['username']=flask.request.form['username']
            return "OK"
            '''
    if password == MasterKey:
        flask.session["username"]=username
        return "OK"
@app.route('/logout',methods=['GET'])
def logout():
    session.pop('username', None)
    return "Logout!"
@app.route('/Del_/<ids>/<password>')
def DelArichvers(ids,password):
    if password != MasterKey:
        return "Password Error!"
    rootdir="Arichvers/"+ids
    filelist=os.listdir(rootdir)
    for f in filelist:
        filepath = os.path.join( rootdir, f )
            if os.path.isfile(filepath):
                os.remove(filepath)
        elif os.path.isdir(filepath):
            shutil.rmtree(filepath,True)
    os.rmdir(rootdir)
    return "OK!"
@app.route('/write')
def write():
    return flask.render_template("post.html")
@app.route('/post',methods=['POST'])
def post():
    title = flask.request.form['title']
    content = flask.request.form['content']
    psw = flask.request.form['masterkey']
    if psw != MasterKey:
        return "Password Error!"
    print title,content
    if title != "" and content != "":
        CreadArichvers(title,content)
        return "OK"
if __name__ == '__main__':
    #print sys.path
    app.run(host='0.0.0.0',port=8082,threaded=True)

